# -*- coding: utf-8 -*-

from odoo import models, fields as odoo_fields, api
from odoo_contrib import models as contrib_models

from ..utils.exceptions import WechatMiniAppException


class MessageTemplate(contrib_models.SchemaModel):
    _name = 'wechat.message_template'

    template_id = odoo_fields.Char(required=True, string='消息模版id')
    name = odoo_fields.Char(required=True, string='消息模版标识名称')
    desc = odoo_fields.Char(string='消息模版描述')
    default = odoo_fields.Boolean(default=False, string='是否为默认模版')
    redirect_path = odoo_fields.Char(string='跳转目标')

    fields = odoo_fields.One2many(
        'wechat.message_template_field',
        'template',
        string='消息模版字段',
    )

    def normalize_data(self, data):
        self.ensure_one()

        if not isinstance(data, dict):
            raise WechatMiniAppException(
                errcode=307001,
            )
        all_fields = []
        normalized = {}
        for field in self.fields:
            if field.required and field.name not in data:
                raise WechatMiniAppException(
                    errcode=307002,
                )
            all_fields.append(field.name)
            if field.default:
                normalized[field.name] = {
                    'value': field.default,
                }

        for k, v in data.items():
            if k not in all_fields:
                continue
            normalized[k] = {
                'value': v,
            }

        return normalized

    @api.model
    def send(self, template_id, targets, data, page=None, emphasis_keyword=None, site=None):
        template = self.sudo().search([
            ('template_id', '=', template_id),
        ], limit=1)
        if not template:
            raise WechatMiniAppException(
                errcode=307003,
            )

        if site is None:
            miniapp = self.env['wechat.miniapp'].sudo().search([
                ('default', '=', True),
            ], limit=1)
        else:
            miniapp = self.env['wechat.miniapp'].sudo().search([
                ('name', '=', site),
            ], limit=1)
        if not miniapp:
            raise WechatMiniAppException(
                errcode=307004,
                params={
                    'site': site
                }
            )
        miniapp = miniapp.get_adaptor()
        data = template.normalize_data(data)

        for target in targets:
            miniapp.send_template_message(
                template_id,
                target,
                data,
                page or template.redirect_path or None,
                emphasis_keyword,
            )


class MessageTemplateField(contrib_models.SchemaModel):
    _name = 'wechat.message_template_field'

    name = odoo_fields.Char(required=True, string='消息模版字段名称')
    required = odoo_fields.Boolean(default=False, string='是否必须设置')
    default = odoo_fields.Char(string='字段默认值')

    template = odoo_fields.Many2one(
        'wechat.message_template',
        ondelete='cascade',
        required=True,
    )
